function parseFile(file)
{
    if (file)
    {
        var r = new FileReader();
        r.onload = function(e) {
            data = parseData(e.target.result);

            $.fancybox({
                'autoSize': false,
                'margin': 20,
                'width': 9999,
                'padding': 0,
                'content': '<div id="container" style="height:inherit" />'
            });

            drawChart(data, $('#container')[0]);
        };
        r.readAsText(file);
    }
    else
    { 
        alert("Failed to load file");
    }
}

function parseI(line)
{
    res = {};
    count = parseInt(line.substr(1,2))
    for(i=0; i<count; ++i)
    {
        s = parseInt(line.substr(3+i*7,2));
        e = parseInt(line.substr(5+i*7,2));
        n = line.substr(7+i*7,3);
        res[n] = [s-1, e];
    }
    return res;
}

function parseB(line, adp)
{
    h = parseInt(line.substr(1,2));
    m = parseInt(line.substr(3,2));
    s = parseInt(line.substr(5,2));   
    rec = {};
    rec.time = ((h*60 + m)*60 + s)*1000;
    rec.pAlt = parseInt(line.substr(25,5));
    rec.gAlt = parseInt(line.substr(30,5));
    for(n in adp)
    {
        a = adp[n];
        rec[n] = parseInt(line.substring(a[0],a[1]));
    }    
    return rec;
}

function parseH(line, header)
{
    if(line.substr(1,14) == 'PTZNUTCOFFSET:')
    {
        p = line.indexOf(':',15);
        header.hours = parseInt(line.substring(15, p));
        header.minutes = parseInt(line.substring(p+1));
    }
    else if(line.substr(1,4) == 'FDTE')
    {
        header.day = parseInt(line.substr(5,2));
        header.month = parseInt(line.substr(7,2));
        header.year = parseInt(line.substr(9,2))+2000;
    }
}

function parseData(text)
{
    header = {};
    data = { time:[], pAlt:[], gAlt:[], RPM:[], CHT:[] };
    lines = text.split('\n');
    for(i in lines)
    {
        line = lines[i];
        switch(line[0])
        {
        case 'H':
            parseH(line, header);
            break;

        case 'I':
            adp = parseI(line);
            adp = { RPM:adp['RPM'], CHT:adp['CHT'] };   // Leave only RPM and CHT
            break;

        case 'B':
            rec = parseB(line, adp);
            rec.RPM = rec.RPM == 0 ? null : rec.RPM * 10;
            if(rec.CHT == 0) rec.CHT = null;
            for(n in data) data[n].push(rec[n]);
            break;
        }
    }
    data.start = Date.UTC(header.year, header.month-1, header.day, header.hours, header.minutes) + data.time[0];
    data.interval = data.time[1] - data.time[0];
    return data;
}


function drawChart(data, container)
{
    colorAlt = '#89A54E';
    colorRPM = '#4572A7';
    colorTemp = '#AA4643';
    dtFormat = "%d %b'%y %H:%M:%S";
    dtFmtArr = [dtFormat, dtFormat, ""];

    top1 = 35;
    interval = 10;
    bottom = 35;

    yHeight = (container.clientHeight-top1-interval-bottom)/2;

    top2 = top1 + yHeight + interval;

    var chart1 = new Highcharts.StockChart(
        {
            chart: {
                renderTo: container,
                zoomType: 'x',
                borderRadius: 0,
            },

            credits: {
                href: 'http://www.wmonkeys.ru/2013/08/flight-chart.html',
                text: 'Winged Monkeys',
            },

            title: {
                text: 'Flight chart'
            },

            rangeSelector: {
                enabled: false,
            },

            navigator: {
                enabled: false,
            },

            scrollbar: {
                enabled: false,
            },

            legend: {
                enabled:false
            },

            tooltip: {
                animation: false,
                shared: true,
                valueDecimals: 0,
            },

            xAxis: [{
                type: 'datetime',
                minTickInterval: 1000,
            }],

            yAxis: [
                {
                    top: top1,
                    height: yHeight,
                    endOnTick: false,
                    minPadding: 0,
                    lineWidth: 2,
                    offset: 0,
                    labels: {
                        formatter: function() {
                            return this.value +' m';
                        },
                        style: {
                            color: colorAlt
                        }
                    },
                    title: {
                        text: 'Altitude',
                        style: {
                            color: colorAlt
                        }
                    },
                },
                {
                    top: top2,
                    height: yHeight,
                    //endOnTick: false,
                    minPadding: 0,
                    lineWidth: 2,
                    offset: 0,
                    opposite: true,
                    title: {
                        text: 'Temperature',
                        style: {
                            color: colorTemp
                        }
                    },
                    labels: {
                        formatter: function() {
                            return this.value +' \xB0C';
                        },
                        style: {
                            color: colorTemp
                        }
                    }
    
                },
                {
                    top: top2,
                    height: yHeight,
                    //endOnTick: false,
                    minPadding: 0,
                    lineWidth: 2,
                    offset: 0,
                    title: {
                        text: 'RPM',
                        style: {
                            color: colorRPM
                        }
                    },
                    labels: {
                        formatter: function() {
                            return this.value +' rpm';
                        },
                        style: {
                            color: colorRPM
                        }
                    },
                }
            ],

            plotOptions:
            {
                series: {
                    lineWidth: 1,
                    marker: {
                        enabled: false,
                        symbol: "circle",
                        states: {
                            hover: {
                                enabled: true,
                                radius: 3,
                            },
                        },
                    },
                    states: {
                        hover: {
                            lineWidth: 2,
                        },
                    },
                    pointStart: data.start,
                    pointInterval: data.interval,
                    dataGrouping: {
                           dateTimeLabelFormats : {
                                millisecond: dtFmtArr,
                                second: dtFmtArr,
                                minute: dtFmtArr,
                                hour:   dtFmtArr,
                                day:    dtFmtArr,
                                week:   dtFmtArr,
                                month:  dtFmtArr,
                                year:   dtFmtArr,
                            }                    
                    },
                    //turboThreshold: 1000,
                    //threshold: null,
                }
            },

            series: [
            {
                name: 'Alt',
                color: colorAlt,
                type: 'spline',
                yAxis: 0,
                data: data.pAlt,
                tooltip: {
                    valueSuffix: ' m'
                }
    
            },
            {
                name: 'GPA',
                type: 'spline',
                color: colorAlt,
                yAxis: 0,
                data: data.gAlt,
                dashStyle: 'shortdot',
                tooltip: {
                    valueSuffix: ' m'
                }
    
            },
            {
                name: 'RPM',
                color: colorRPM,
                type: 'spline',
                yAxis: 2,
                data: data.RPM,
            },
            {
                name: 'Temp',
                type: 'spline',
                color: colorTemp,
                yAxis: 1,
                data: data.CHT,
                tooltip: {
                    valueSuffix: ' \xB0C'
                }
            },
            ]
        }
    );
}
